import { Component, Layers, Node, UITransform, Color } from "cc"
import { ungzip } from "pako"
// import { QualiyColor } from "../common/Contsant"

export const createUINode = (name?: string | any) => {
    const node = new Node(name || '')
    node.addComponent(UITransform)
    node.layer = 1 << Layers.nameToLayer('UI_2D')
    return node
}

/** 深拷贝 */
export const deepClone = (obj: any) => {
    if (obj === null || typeof obj !== 'object') {
        return obj
    }
    const res = Array.isArray(obj) ? [] : {} as any
    for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            res[key] = deepClone(obj[key]) as any
        }
    }
    return res
}

/** 获取component组件的名字 */
export const getComponentName = (com: Component) => {
    let str = com.name
    let start = str.indexOf('<');
    if (start === -1) return ''
    return str.substring(0, start);
}

/**
 * 代码休眠时间
 * @param ms 毫秒
 */
export const sleep = (ms: number) => {
    return new Promise<void>((resolve) => {
        setTimeout(() => {
            resolve();
        }, ms)
    });
}

/** 获取唯一id */
export const getUUID = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; let uuid = '';
    for (let i = 0; i < 32; i++) { if (i === 8 || i === 12 || i === 16 || i === 20) { uuid += '-'; } else { uuid += chars.charAt(Math.floor(Math.random() * chars.length)); } }
    return uuid;
}

// /** 通过品质给图片设置颜色 */
// export const setInnerColorByQuality = (node: Node, qualty: number | string) => {

//     const colorType = {
//         1: 'white',
//         2: 'green',
//         3: 'blue',
//         4: 'purple',
//         5: 'orange',
//         6: 'red',
//     }
//     const color = QualiyColor[colorType[Number(qualty)]]
//     node.getChildByName('inner').uiSprite.color = new Color(...color)
//     node.uiSprite.color = new Color(color[0] / 2, color[1] / 2, color[2] / 2, color[3])
// }

/** ui节点映射 */
export const ui2map = (parent: Node): { [name: string]: Node } => {

    const view = {}
    const bindView = (parent: Node) => {
        let items = parent.children;
        for (let i = 0; i < items.length; i++) {
            view[items[i].name] = items[i]
            bindView(items[i])
        }
    }
    bindView(parent)
    return view
}

/**
 * 解压缩并反序列化数据
 * @param data - Base64 编码的压缩数据字符串
 * @returns 解压后的对象或空对象（如果发生错误）
 */
export const decompressData = (data: any): any => {
    try {
        // 将 Base64 编码的字符串转换为 Uint8Array
        const compressedUint8Array = base64ToArrayBuffer(data);

        // 使用 Pako 进行 Gzip 解压
        const decompressedUint8Array = ungzip(compressedUint8Array, { to: 'string' });

        // 将解压后的数据解析为 JSON 对象
        const originalObject = JSON.parse(decompressedUint8Array);
        return originalObject;

    } catch (err) {
        console.error("解压或解析时出错:", err);
        return {};
    }
};

// 辅助函数：将 Base64 编码的字符串转换为 ArrayBuffer
function base64ToArrayBuffer(base64: string): Uint8Array {
    const binaryString = atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes;
}